package com.jason.quectel0805.activities;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jason.quectel0805.R;
import com.jason.quectel0805.entities.ResponseData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class JsonActivity extends AppCompatActivity {
    private static final String TAG = "jasonwan";
    private TextView tvShow;
    private ImageView ivShow;
    private String jsonStr = "{\n" +
            "\t\"data\":{\n" +
            "\t\t\"curPage\": 1,\n" +
            "\t\t\"datas\": [\n" +
            "\t\t\t{\n" +
            "\t\t\t\"link\": \"https://juejin.cn/post/7129157665732689934\",\n" +
            "\t\t\t\"niceDate\": \"3小时前\",\n" +
            "\t\t\t\"title\": \"&ldquo;终于懂了&rdquo; 系列：组件化框架 ARouter 完全解析（二）APT技术\"\n" +
            "\t\t\t}, \n" +
            "\t\t\t{\n" +
            "\t\t\t\"link\": \"https://mp.weixin.qq.com/s/LWDOaAQIkRnst2GLCAeAsw\",\n" +
            "\t\t\t\"niceDate\": \"6小时前\",\n" +
            "\t\t\t\"title\": \"三个值得深入思考的 Android 问答分享（第 2 期）\"\n" +
            "\t\t\t}\n" +
            "\t\t]\n" +
            "\n" +
            "\t},\n" +
            "\t\"errorCode\":\"1\",\n" +
            "\t\"errorMsg\":\"获取成功\"\n" +
            "}";

    String imgAddress = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic4.zhimg.com%2Fv2-fb51823f569bbe8af4c9adf2a0bd516f_r.jpg&refer=http%3A%2F%2Fpic4.zhimg" +
            ".com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1662542628&t=a33756dfe2aef8d13629bdee8654d4eb";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json);

        tvShow = findViewById(R.id.tv_json_show);
        ivShow = findViewById(R.id.iv_show);

        //通过JsonObject和JsonArray手动解析json数据
        //parseJsonData(jsonStr);
        //    利用Gson自动解析json数据
        parseJsonDataByGson(jsonStr);

        String jsonStr = generateJsonStr();
        Log.d(TAG, "onCreate: jsonStr:\n" + jsonStr);
    }

    private String generateJsonStr() {
        ResponseData responseData = new ResponseData();
        responseData.setErrorCode("1");
        responseData.setErrorMsg("请求成功");
        ResponseData.ResponseDataBody body = new ResponseData.ResponseDataBody();
        body.setCurPage("0");
        List<ResponseData.ResponseDataBody.Article> list = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd E hh-mm-ss");
        for (int i = 0; i < 10; i++) {
            ResponseData.ResponseDataBody.Article article = new ResponseData.ResponseDataBody.Article();
            article.setTitle("从百草园到三味书屋");
            article.setLink("https://www.quectel.com/");
            article.setNiceDate(simpleDateFormat.format(Calendar.getInstance().getTime()));
            list.add(article);
        }
        body.setDatas(list);
        responseData.setData(body);
        //将responsedata对象转成json字符串
        Gson gson = new Gson();
        String jsonStr = gson.toJson(responseData);
        return jsonStr;
    }

    private void parseJsonDataByGson(String jsonStr) {
        Gson gson = new Gson();
        ResponseData responseData = gson.fromJson(jsonStr, ResponseData.class);
        Log.d(TAG, "parseJsonDataByGson: " + responseData.toString());
    }

    /**
     * 解析json数据的目的：将带有json格式的字符串转化成我们自己定义的java对象，以便操作
     *
     * @param jsonStr
     */
    private void parseJsonData(String jsonStr) {
        try {
            JSONObject jsonObject = new JSONObject(jsonStr);
            ResponseData responseData = new ResponseData();

            String errorCode = jsonObject.getString("errorCode");
            String errorMsg = jsonObject.getString("errorMsg");
            responseData.setErrorCode(errorCode);
            responseData.setErrorMsg(errorMsg);

            JSONObject jsonObjectData = jsonObject.getJSONObject("data");

            ResponseData.ResponseDataBody responseDataBody = new ResponseData.ResponseDataBody();

            String curPage = jsonObjectData.getString("curPage");
            responseDataBody.setCurPage(curPage);

            JSONArray jsonArrayDatas = jsonObjectData.getJSONArray("datas");
            ArrayList<ResponseData.ResponseDataBody.Article> articleList = new ArrayList<>();
            for (int i = 0; i < jsonArrayDatas.length(); i++) {
                JSONObject object = (JSONObject) jsonArrayDatas.get(i);
                String link = object.getString("link");
                String niceDate = object.getString("niceDate");
                String title = object.getString("title");
                ResponseData.ResponseDataBody.Article article = new ResponseData.ResponseDataBody.Article();
                article.setLink(link);
                article.setNiceDate(niceDate);
                article.setTitle(title);
                articleList.add(article);
            }
            responseDataBody.setDatas(articleList);
            responseData.setData(responseDataBody);

            Log.d(TAG, "parseJsonData: responseData=" + responseData.toString());


            StringBuilder sbContent = new StringBuilder();
            List<ResponseData.ResponseDataBody.Article> list = responseData.getData().getDatas();
            for (ResponseData.ResponseDataBody.Article article : list) {
                sbContent.append("文章标题：").append(article.getTitle()).append("\n")
                        .append("文章发表时间：").append(article.getNiceDate()).append("\n")
                        .append("文章链接：").append(article.getLink()).append("\n\n");
            }

            tvShow.setText(sbContent.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载网络图片
     *
     * @param view
     */
    public void loadNetImg(View view) {
        Glide.with(this).load(imgAddress).into(ivShow);
        //new Thread(new Runnable() {
        //    @Override
        //    public void run() {
        //        OkHttpClient okHttpClient = new OkHttpClient();
        //
        //        Request.Builder builder = new Request.Builder();
        //        Request request = builder.url(imgAddress).build();
        //        try {
        //            Response response = okHttpClient.newCall(request).execute();
        //            byte[] bytes = response.body().bytes();
        //            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        //            Message message = Message.obtain();
        //            message.what = 1;
        //            message.obj = bitmap;
        //            mHander.sendMessage(message);
        //        } catch (IOException e) {
        //            e.printStackTrace();
        //        }
        //    }
        //}).start();
    }

    private Handler mHander = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Bitmap bitmap = (Bitmap) msg.obj;
                    ivShow.setImageBitmap(bitmap);
                    break;
            }

        }
    };
}